<template>
  <view class="chat-detail-container">

    <!-- 加入组队弹窗（成员列表） -->
    <u-popup v-model="showJoinTeamPopup" mode="center" :mask-close-able="false" class="join-team-popup">
      <view class="join-team-content">
        <text class="join-title">组队成员列表</text>
        <view class="member-list">
          <view v-for="member in teamMemberList" :key="member.user_id" class="member-row">
            <u-avatar :src="member.image ? member.image.replace(/^\//, '') : '/static/icons/default-avatar.png'"
              size="48"  />
            <view class="member-info">
              <text class="member-name">{{ member.nickname || '匿名用户' }}</text>
              <view class="member-details">
                <text class="member-gender">{{ member.gender === '1' || member.gender === 1 ? '男' : '女' }}</text>
                <text class="member-age">{{ member.age ? member.age + '岁' : '未知' }}</text>
              </view>
            </view>
          </view>
        </view>
        <u-button type="primary" class="join-btn" :disabled="isTeamFull" @click="handleJoinTeam">
          {{ isTeamFull ? '已满员' : '加入组队' }}
        </u-button>
      </view>
    </u-popup>

    <!-- 组队信息横幅 -->
    <view class="team-banner" v-if="isTeamChat && teamInfo && Object.keys(teamInfo).length">
      <view class="team-info">
        <view class="team-title-row">
          <view class="team-title">{{ teamInfo.title || '未知组队' }}</view>
          <view class="gender-tag all"  v-if="teamInfo.sex == 1">男女不限</view>
          <view class="gender-tag nan" v-if="teamInfo.sex == 2">仅限男生</view>
          <view class="gender-tag nv" v-if="teamInfo.sex == 3">仅限女生</view>
        </view>
       <view class="team-member-list">
						<text class="team-shop">{{ teamInfo.shop_title || teamInfo.shop || '未知店铺' }}</text>
						<view class="team-time">
							<text>{{ teamInfo.time || '未知时间' }}</text>
						</view>
					</view>
        <view class="team-status">
          <view class="member-info">
            <u-avatar :src="globalConfig.site_url + teamInfo.user_info.image" size="64"/>
            <text class="member-count">{{ teamInfo.members || teamInfo.currentMembers || 0 }}/{{ teamInfo.max_members ||
              teamInfo.maxMembers || 0 }}人</text>
          </view>
          <view class="distance-info">
            <u-icon name="map" size="24" color="#fff" class="status-icon"></u-icon>
            <text class="distance">{{ teamInfo.distance || '未知距离' }}</text>
          </view>
          <!-- <u-icon name="share" size="28" color="#fff" class="share-icon"></u-icon> -->
        </view>
      </view> 
      <u-button size="mini" class="exit-btn-card" @click="handlejiesanTeam" v-if="teamInfo.user_info.id == userId">解散群组</u-button>
       <u-button size="mini" class="exit-btn-card" @click="handleExitTeam" v-else>退出组队</u-button>
    </view>

    <!-- 消息区域 -->
    <scroll-view class="message-list" scroll-y>
      <view v-for="(msg, index) in messageList" :key="index" class="message-item"
        :class="{ 'self-message': msg.isSelf, 'other-message': !msg.isSelf }"   @click="navigateToUserHome(msg.user_id)" >
        <!-- 对方消息：头像在前 -->
        <u-avatar v-if="!msg.isSelf" class="avatar" :src="msg.avatar || defaultAvatar"></u-avatar>
        <view class="message-bubble" :class="{ 'self-bubble': msg.isSelf, 'other-bubble': !msg.isSelf }">
          <!-- <text class="sender-name" v-if="!msg.isSelf">{{ msg.senderName }}</text> -->
          <text class="message-content">{{ msg.content }}</text>
        </view>
        <!-- 自己消息：头像在后 -->
        <u-avatar v-if="msg.isSelf" class="avatar" :src="msg.avatar || defaultAvatar"   @click="navigateToUserHome(msg.user_id)" ></u-avatar>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-area">
      <u-icon name="face" size="36" color="#888"></u-icon>
      <u-input v-model="inputMessage" class="message-input" placeholder="输入消息..."
        placeholder-style="color: #888;"></u-input>
      <view class="send-btn" @click="sendMessage">发送</view>
    </view>
  </view>
</template>

<script>
import { getChatHistory, sendChatMessage, getTeamMember, joinTeam, exitTeam, saveMessage,disbandTeam } from '@/api/user.js'
import { mapGetters, mapState } from 'vuex';
export default {
  data() {
    return {
    userId: '',
      chatId: '',
      chatType: '', // 'single' or 'group'
      isTeamChat: false,
      chatName: '',
      userName: '',
      userAvatar: '',
      userAge: '',
      distance: '',
      memberCount: 0,
      myAvatar: '/static/icons/default-avatar.png',
      messageList: [],
      myMessageList: [],
      inputMessage: '',
      teamInfo: {
        title: '',
        shop: '',
        startTime: '',
        endTime: '',
        currentMembers: 0,
        maxMembers: 0,
        distance: ''
      },
      showJoinTeamPopup: false,
      teamMemberList: [],
      isTeamFull: false,
      joinMemberCount: 1
    }
  },
  computed: {
    isGroupChat() {
      return this.chatType === 'group';
    },
    ...mapGetters(['getUserInfo']),
    ...mapState({
      globalConfig: state => state.config,
      userLocation: state => state.location,
      userInfo: state => state.userInfo,
    })
  },
  onLoad(options) {
    console.log(this.getUserInfo, 'getUserInfo');
    console.log('页面参数:', options);
    this.chatId = options.teamId
    // 解析并存储组队信息到Vuex
    if (options.teamInfo) {
      try {
        const teamInfo = JSON.parse(decodeURIComponent(options.teamInfo))
        console.log('解析到的组队信息:', teamInfo);
        this.teamInfo = teamInfo
        this.$store.commit('SET_TEAM_INFO', teamInfo)
      } catch (e) {
        console.error('解析组队信息失败:', e)
      }
    } else {
      console.warn('未接收到组队信息');
    }
    this.chatType = options.type || 'single'
    this.userName = options.nickName || ''
    // 修复用户ID获取逻辑，优先从store获取
    // 增强用户ID获取调试
    // 增强用户ID获取与错误处理
    const storeUser = this.userInfo;
    const storeUserId = storeUser?.id;
    // 仅使用store中的用户ID，options.userId是对方用户ID，不应作为当前用户ID fallback
    this.userId = String(storeUserId || '');
    if (!this.userId) {
      console.error('用户ID获取失败:', { storeUser, options });
      uni.showToast({ title: '用户信息加载失败', icon: 'error' });
    }
    console.log('用户ID获取调试:', { storeUserId, optionsUserId: options.userId, finalUserId: this.userId });
    console.log('当前用户ID:', this.userId);
    this.isTeamChat = options.isTeamChat === 'true'
    console.log('是否为团队聊天:', this.isTeamChat);
    this.getChatHistory()

    // 设置轮询获取最新消息
    this.pollingTimer = setInterval(() => {
      this.getChatHistory();
    }, 3000);

    // 进入页面先弹窗选择人数
    if (this.isTeamChat) {
      this.showJoinTeamPopup = true;
      this.getTeamMemberList();
    }
  },
  methods: {
    navigateToUserHome(userId) {
      if (!userId) {
        uni.showToast({ title: '用户信息获取失败', icon: 'none' });
        return;
      }
      uni.navigateTo({ url: `/pages/other/profile?id=${userId}` })
    },
    onUnload() {
      // 清理轮询定时器
      if (this.pollingTimer) {
        clearInterval(this.pollingTimer);
        this.pollingTimer = null;
      }
    },
    navigateBack() {
      uni.navigateBack()
    },
    navigateToUserProfile(userId) {
      // 跳转到用户个人资料页
      uni.navigateTo({
        url: `/pages/other/profile?id=${userId || '123'}`
      });
    },
    showGroupMembers() {
      // 跳转到群成员列表页
      uni.navigateTo({
        url: `/pages/chat/group-members?id=${this.chatId}`
      });
    },
    async getChatHistory() {
      try {
        const res = await getChatHistory({
          chat_id: this.chatId,
          type: this.isTeamChat ? 1 : 2
        });
        let list = [];
        if (res.data && res.data.code === 1) {
          // 兼容分页结构和数组结构
          // 数据倒叙
          if (Array.isArray(res.data.data)) {
            list = res.data.data.reverse();
          } else if (res.data.data && Array.isArray(res.data.data.data)) {
            list = res.data.data.data.reverse();
          } else {
            list = [];
          }
          console.log(list, 'messageList');

          // 渲染 info、users.nickname、users.image、users_id，兼容单聊和群聊所有字段
          // 修复消息顺序并确保isSelf判断正确
          this.messageList = list.map(msg => {
            // senderId 兼容单聊和群聊所有可能字段，优先使用sender_id
            let senderId = String(msg.sender_id || msg.users.id || msg.users_id || msg.senderId || msg.user_id || msg.id || '');
            let senderName = msg.users?.nickname ?? msg.senderName ?? msg.nickname ?? '匿名用户';
            let avatar = '';
            if (msg.users?.image) {
              avatar = this.globalConfig.site_url + msg.users.image;
            }
            return {
              content: msg.info ?? msg.content ?? '',
              senderId,
              senderName,
              avatar,
              createtime: msg.createtime || Date.now(), // 添加时间戳用于排序
              isSelf: senderId === this.userId
            };
          }).filter(msg => msg.content && msg.content.trim());
          // 按创建时间正序排列消息（ oldest -> newest ）
          // 按创建时间正序排列( oldest -> newest )并处理无效时间
          this.messageList = this.messageList.sort((a, b) => {
            const timeA = typeof a.createtime === 'number' ? a.createtime : 0;
            const timeB = typeof b.createtime === 'number' ? b.createtime : 0;
            return timeA - timeB;
          });
        } else {
          uni.showToast({ title: res.data.msg || '获取聊天记录失败', icon: 'none' });
        }
      } catch (error) {
        console.error('获取聊天记录失败:', error);
        uni.showToast({ title: '获取聊天记录失败', icon: 'none' })
      }
    },
    async getTeamMemberList() {
      try {
        // 调试信息：打印API请求参数
        console.log('获取团队成员 - team_id:', this.chatId);
        const res = await getTeamMember({ team_id: this.chatId });
        // 调试信息：打印API响应
        console.log('团队成员API响应:', res);
        if (res.data && res.data.code === 1) {
          this.teamMemberList = res.data.data || [];
          // 判断当前用户是否已在成员列表
          const alreadyInTeam = this.teamMemberList.some(m => String(m.user_id) === String(this.userId));
          const max = this.teamInfo.max_members || this.teamInfo.maxMembers || 9;
          this.isTeamFull = this.teamMemberList.length >= max;
          this.showJoinTeamPopup = !alreadyInTeam;
        } else {
          // API返回错误时使用模拟数据
          console.warn('获取成员失败，使用模拟数据');
          this.teamMemberList = [
            { user_id: 4, nickname: "明天", image: "/uploads/20250710/90c61628d1844cb98c2380ec5fa5b169.png", gender: "1", age: 55 },
            { user_id: 3, nickname: "3", image: null, gender: "0", age: "" }
          ];
          this.isTeamFull = false;
          // 判断当前用户是否已在模拟成员列表
          const alreadyInTeam = this.teamMemberList.some(m => String(m.user_id) === String(this.userId));
          this.showJoinTeamPopup = !alreadyInTeam;
          uni.showToast({ title: res.data?.msg || '获取成员失败，已加载模拟数据', icon: 'none' });
        }
      } catch (error) {
        // 网络错误时使用模拟数据
        console.error('获取成员网络错误:', error);
        this.teamMemberList = [
          { user_id: 4, nickname: "明天", image: "/uploads/20250710/90c61628d1844cb98c2380ec5fa5b169.png", gender: "1", age: 55 },
          { user_id: 3, nickname: "3", image: null, gender: "0", age: "" }
        ];
        this.isTeamFull = false;
        // 判断当前用户是否已在模拟成员列表
        const alreadyInTeam = this.teamMemberList.some(m => String(m.user_id) === String(this.userId));
        this.showJoinTeamPopup = !alreadyInTeam;
        uni.showToast({ title: '网络错误，已加载模拟数据', icon: 'none' });
      }
    },
    async handleJoinTeam() {
      if (this.isTeamFull) return;
      try {
        const res = await joinTeam({ team_id: this.chatId });
        if (res.data && res.data.code === 1) {
          uni.showToast({ title: '已加入组队', icon: 'success' });
          this.showJoinTeamPopup = false;
          this.getTeamMemberList();
        } else {
          uni.showToast({ title: res.data.msg || '加入失败', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '网络错误，加入失败', icon: 'none' });
      }
    },
    async handleExitTeam() {
      try {
        const res = await exitTeam({ team_id: this.chatId });
        if (res.data && res.data.code === 1) {
          uni.showToast({ title: '已退出组队', icon: 'success' });
          uni.navigateBack();
          uni.$emit('refreshPage', 'message');
        } else {
          uni.showToast({ title: res.data.msg || '退出失败', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '网络错误，退出失败', icon: 'none' });
      }
    },
    async handlejiesanTeam (){
       try {
        const res = await disbandTeam({ team_id: this.chatId });
        if (res.data && res.data.code === 1) {
          uni.showToast({ title: '已解散组队', icon: 'success' });
          uni.navigateBack();
        } else {
          uni.showToast({ title: res.data.msg || '解散失败', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '网络错误，解散失败', icon: 'none' });
      }
    },
    async sendMessage() {
      if (!this.inputMessage.trim()) {
        uni.showToast({ title: '请输入消息内容', icon: 'none' });
        return;
      }
      try {
        const res = await saveMessage({
          type: this.isTeamChat ? 1 : 2,
          chat_id: this.chatId,
          info: this.inputMessage.trim()
        });
        if (res.data && res.data.code === 1) {
          this.getChatHistory();
          this.inputMessage = '';
          this.scrollToBottom();
        } else {
          uni.showToast({ title: res.data.msg || '发送失败', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '网络错误，发送失败', icon: 'none' });
      }
    },
    // 滚动到底部
    scrollToBottom() {
      uni.pageScrollTo({ scrollTop: 99999, duration: 0 });
    }
  }
}
</script>

<style scoped lang="less">
.chat-detail-container {
  min-height: 100vh;
  background-color: #000;
  color: #fff;
}

.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 32rpx;
  background-color: #1a1a1a;
  position: relative;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 500;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.exit-btn {
  margin-left: 24rpx;
}

.team-banner {
  background-color: #57C8F2;
  border-radius: 16rpx;
  margin: 16rpx;
  padding: 24rpx;
  color: #fff;
  position: relative;
}

.team-title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.team-title {
  font-size: 32rpx;
  font-weight: bold;
}

.gender-tag {
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 16rpx;
  padding: 4rpx 16rpx;
  font-size: 24rpx;
}
.all{
  background-color:  linear-gradient(180deg, #1976d2 50%, #FF8DD3 50%);
}

.nan{
  background-color: #1976d2;
}

.nv{
  background-color: #FF8DD3;
}

.team-member-list{
	
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
	align-items: center;
.team-shop {
	font-size: 26rpx;
	margin-bottom: 12rpx;
	opacity: 0.9;
	border: 1px solid #fff;
	border-radius: .5rem;
	padding: .1rem .5rem;
}

.team-time {
	display: flex;
	justify-content: space-between;
	font-size: 24rpx;
	margin-bottom: 16rpx;
	opacity: 0.9;
	border: 1px solid #fff;
	border-radius: .5rem;
	padding: .1rem .5rem;
}

}

.team-status {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 24rpx;
}

.member-info,
.distance-info {
  display: flex;
  align-items: center;
}

.status-icon {
  margin-right: 8rpx;
}

.share-icon {
  opacity: 0.9;
}

.message-list {
  padding: 16rpx;
  height: calc(100vh - 120rpx);
}

.message-item {
  display: flex;
  margin-bottom: 24rpx;
  /* max-width: 85%; */
}

.other-message {
  align-items: flex-start;
}

.self-message {
  flex-direction: row-reverse;
  align-items: flex-start;
  flex-direction: row;
  margin-left: auto;
}

.avatar {
  border-radius: 50%;
}

.message-bubble {
  position: relative;
  padding: 18rpx 24rpx;
  border-radius: 18rpx;
  max-width: calc(100% - 80rpx);
}

.other-bubble {
  background-color: #2d2d2d;
  margin-left: 16rpx;
}

.self-bubble {
  background-color: #57C8F2;
  margin-right: 16rpx;
}

.sender-name {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
  display: block;
}

.message-content {
  font-size: 30rpx;
  line-height: 1.5;
}

.input-area {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background-color: #1a1a1a;
  border-top: 1px solid #333;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.message-input {
  flex: 1;
  background-color: #333;
  border-radius: 32rpx;
  padding: 16rpx 24rpx;
  margin: 0 16rpx;
  color: #fff;
  height: 68rpx;
  font-size: 28rpx;
}

.send-btn {
  background-color: #409EFF;
  border-radius: 50rpx;
  padding: 15rpx 40rpx;
  font-size: 32rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  transition: background-color 0.3s;
  margin-left: 10rpx;
}

.send-btn:hover {
  background-color: #337ecc;
}

.message-item {
  display: flex;
  margin: 10rpx 20rpx;
  align-items: flex-end;
}

.other-message {
  justify-content: flex-start;
}

.self-message {
  /* justify-content: flex-end; */
  justify-content: flex-end;
}

.avatar {
  border-radius: 50%;
}

.message-bubble {
  position: relative;
  padding: 18rpx 24rpx;
  border-radius: 18rpx;
  max-width: calc(100% - 80rpx);
}

.other-bubble {
  background-color: #2d2d2d;
  margin-left: 16rpx;
}

.self-bubble {
  background-color: #57C8F2;
  margin-right: 16rpx;
}

.sender-name {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
  display: block;
}

.message-content {
  font-size: 30rpx;
  line-height: 1.5;
}

.invite-btn {
  background-color: #57C8F2;
  width: 68rpx;
  height: 68rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 12rpx;
}


.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #f5f5f5;
  border-bottom: 1rpx solid #eee;
}

.team-info {
  flex: 1;
}

.team-title {
  font-size: 34rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
  display: block;
}

.team-members {
  font-size: 26rpx;
  color: #666;
}

.join-team-popup {
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
}

.join-team-content {
  background: #23232b;
  border-radius: 32rpx;
  box-shadow: 0 12rpx 48rpx rgba(0, 0, 0, 0.45);
  padding: 64rpx 40rpx 48rpx 40rpx;
  min-width: 600rpx;
  min-height: 480rpx;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  overflow: visible;
}

.join-title {
  font-size: 36rpx;
  color: #fff;
  font-weight: bold;
  margin-bottom: 40rpx;
  letter-spacing: 2rpx;
}

.member-list {
  width: 100%;
  max-height: 48vh;
  min-height: 120rpx;
  overflow-y: auto;
  margin-bottom: 40rpx;
  padding-right: 8rpx;
  background: transparent;
}

.member-row {
  display: flex;
  align-items: center;
  padding: 18rpx 0;
  border-bottom: 1px solid #333;
  background: rgba(44, 44, 54, 0.7);
  border-radius: 18rpx;
  margin-bottom: 12rpx;
  transition: box-shadow 0.2s;
  min-height: 68rpx;
}

.member-row:last-child {
  border-bottom: none;
}

.member-row .u-avatar {
  border: 3rpx solid #57C8F2;
  box-shadow: 0 2rpx 8rpx rgba(87, 200, 242, 0.15);
}

.member-info {
  /* margin-left: 22rpx; */
  display: flex;
  /* flex-direction: column; */
}

.member-name {
  font-size: 30rpx;
  color: #fff;
  font-weight: 500;
  margin-bottom: 6rpx;
}

.member-details {
  display: flex;
  gap: 18rpx;
}

.member-gender {
  font-size: 24rpx;
  color: #57C8F2;
  background: rgba(87, 200, 242, 0.12);
  border-radius: 10rpx;
  padding: 2rpx 12rpx;
}

.member-age {
  font-size: 24rpx;
  color: #bbb;
}

.invite-btn {
  background-color: #57C8F2;
  width: 68rpx;
  height: 68rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(87, 200, 242, 0.18);
}

.join-btn {
  width: 100%;
  font-size: 32rpx;
  border-radius: 20rpx;
  margin-top: 12rpx;
  font-weight: 500;
  box-shadow: 0 4rpx 16rpx rgba(87, 200, 242, 0.12);
}

.exit-btn-card {
  position: absolute;
  right: 32rpx;
  bottom: 32rpx;
  z-index: 2;
}
</style>